package com.example.demo.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.demo.util.HttpClientUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: yby
 * @desc:
 * @date: 2024/9/23 9:27
 */
@RestController
@RequestMapping("/auth2")
@Slf4j
public class Auth2Login {

   @RequestMapping(value = {"/login","alogin"})
   public String login(HttpServletRequest request, HttpServletResponse response) throws IOException {
      String body = getRequestBody(request);

      log.info("start--------------");
      String client_id  =  "Q0Yjg5YmYzMTJiMmViZWFhMmIZmIzMjcwOTRjZmM1ND";
      String client_secret = "1R8uEGOHsaP38TpGlrXlwW1s2";
      String redirect_uri = "http://110.40.188.125/"; // http://110.40.188.125/  https://www.baidu.com
      String domain = "portal-test.aigccn.net";
      String state = "success";
      String account = "18888888888";
      String pwd = "Aa123456*";

      // 用户授权：
      //url = "https://{domain}/portal/oauth/authorize?response_type=code&client_id={client_id}&redirect_uri={redirect_uri}&state={state}";
      // https://portal-test.aigccn.net/portal/oauth/authorize?response_type=code&client_id=Q0Yjg5YmYzMTJiMmViZWFhMmIZmIzMjcwOTRjZmM1ND&redirect_uri=https://www.baidu.com&state=params
      String url = "https://"+domain+"/portal/oauth/authorize?response_type=code&client_id="+client_id+"&redirect_uri="+redirect_uri+"&state="+state;
//      String userAccess = HttpClientUtils.doGet(url);
//      log.info("用户授权："+JSONUtil.toJsonStr(userAccess));


//      String code  = userAccess;
//      // 授权后重定向：
//      String tokenUrl = "https://"+domain+"/api/system/oauth2/token";
////      String tokenUrl = "https://"+domain+"/api/system/oauth2/token?client_id="+client_id+"&client_secret="+client_secret+"&grant_type=authorization_code&code="+code+"&redirect_uri="+redirect_uri+"&state="+state;
//      Map<String,String> param = new HashMap<>();
//      param.put("client_id",client_id);
//      param.put("client_secret",client_secret);
//      param.put("grant_type","authorization_code");
//      param.put("code",code);
//      param.put("state",state);
//
//      String response = HttpClientUtils.doPost(tokenUrl, param);
//      log.info("授权后重定向：" +JSONUtil.toJsonStr(response));
//
//      String token = "";
//      // 访问平台user信息
//      String userUrl = "https://"+domain+"/api/system/oauth2/user/get";
//      // 请求投添加：  Authorization : bearer {access_token}
//      Map<String, String> headers3 = new HashMap<>();
//      headers3.put("Authorization","bearer "+token);
//      String userInfo = HttpClientUtils.doGet(userUrl, headers3);
//      log.info("请求用户信息：" +JSONUtil.toJsonStr(userInfo));
       log.info("end-------------");
      response.sendRedirect(url);
       return "";
   }

   public static void main(String[] args) throws IOException {
      log.info("start--------------");
      String client_id  =  "Q0Yjg5YmYzMTJiMmViZWFhMmIZmIzMjcwOTRjZmM1ND";
      String client_secret = "1R8uEGOHsaP38TpGlrXlwW1s2";
      String redirect_uri = "https://www.baidu.com";
      String domain = "portal-test.aigccn.net";
      String state = "success";
      String code = "d8711ea09a3346a48619558d63b2dde1";
      String account = "18888888888";
      String pwd = "Aa123456*";

      // 用户授权：
      //url = "https://{domain}/portal/oauth/authorize?response_type=code&client_id={client_id}&redirect_uri={redirect_uri}&state={state}";
      Map<String, String> headers1 = new HashMap<>();
      String url = "https://"+domain+"/portal/oauth/authorize?response_type=code&client_id="+client_id+"&redirect_uri="+redirect_uri+"&state="+state;
      String userAccess1 = HttpClientUtils.doGet(url);
      log.info("用户授权："+JSONUtil.toJsonStr(userAccess1));








//      String code  = userAccess;
//      // 授权后重定向：
      String tokenUrl = "https://"+domain+"/api/system/oauth2/token";
//      String tokenUrl = "https://"+domain+"/api/system/oauth2/token?client_id="+client_id+"&client_secret="+client_secret+"&grant_type=authorization_code&code="+code+"&redirect_uri="+redirect_uri+"&state="+state;
      Map<String,String> param = new HashMap<>();
      param.put("client_id",client_id);
      param.put("client_secret",client_secret);
      param.put("grant_type","authorization_code");
      param.put("code",code);
      param.put("state",state);

      String response = HttpClientUtils.doPost(tokenUrl, param);
      log.info("授权后重定向：" + JSONUtil.toJsonStr(response));
      JSONObject jsonObject = JSONUtil.parseObj(response);
      String access_token = jsonObject.getJSONObject("data").getStr("access_token");
      log.info("access_token:"+access_token);

      String token = "2fa6d2bfa70e490e80b266e3709f9c8f";
      // 访问平台user信息
      String userUrl = "https://"+domain+"/api/system/oauth2/user/get";
      // 请求投添加：  Authorization : bearer {access_token}
      Map<String, String> headers3 = new HashMap<>();
      headers3.put("Authorization",access_token);
      headers3.put("Content-Type","application/x-www-form-urlencoded");
      String userInfo = HttpClientUtils.doGet(userUrl, headers3);
      log.info("请求用户信息：" + JSONUtil.toJsonStr(userInfo));

   }

   private String getRequestBody(HttpServletRequest req) {
      StringBuilder stringBuilder = new StringBuilder();
      BufferedReader bufferedReader = null;
      try {
         InputStream inputStream = req.getInputStream();
         if (inputStream != null) {
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            char[] charBuffer = new char[128];
            int bytesRead = -1;
            while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
               stringBuilder.append(charBuffer, 0, bytesRead);
            }
         } else {
            stringBuilder.append("");
         }
      } catch (IOException ex) {
      } finally {
         if (bufferedReader != null) {
            try {
               bufferedReader.close();
            } catch (IOException ex) {
            }
         }
      }
      return stringBuilder.toString();
   }

}
